<template>
  <div class="article-page">
    <nav class="my-nav van-hairline--bottom">
      <a :class="{active: type == 'weight_desc'}" @click="changeTab('weight_desc')" href="javascript:;">推荐</a>
      <a :class="{active: type != 'weight_desc'}" @click="changeTab()" href="javascript:;">最新</a>
      <div class="logo"><img src="@/assets/logo.png" alt="" /></div>
    </nav>
    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="onLoad"
    >
      <!-- 列表 -->
      <!-- 这个是组件，你写@是代表加事件吗？不是，是代表监听自定义事件（相当于子传父用的） -->
      <article-item
        v-for="item in list"
        :key="item.id"
        :item="item"
      ></article-item>
    </van-list>
  </div>
</template>

<script>
import { articleListAPI } from '@/api/artcile'
export default {
  name: 'article-page',
  data () {
    return {
      type: 'weight_desc',
      list: [],
      loading: false,
      finished: false,
      page: 1
    }
  },
  methods: {
    // 栏目分类被点
    changeTab (type) {
      // 保存被点的名字特征做切换类
      this.type = type
      // 先清空原本的内容
      this.list = []
      // 有可能页码变了，所以还得恢复页码
      this.page = 1
      // 还得把finished和loading这些值通通都恢复成false
      this.loading = this.finished = false
      // 重新加载数据
      this.onLoad()
    },
    async onLoad () {
      // 发请求
      const res = await articleListAPI({
        current: this.page,
        pageSize: 10,
        // 不传就给undefined
        sorter: this.type
      })
      // 每次加载完让页码+1
      this.page++
      // 不能用=进行赋值，因为这样会覆盖原本的数据
      // this.list = res.data.rows
      // 我们应该是在原本有的数据上再进行追加才不会覆盖
      // 注意前面要加展开运算符，不然它就不是一条一条加进数组的
      this.list.push(...res.data.rows)

      // 把loading改为false代表本次加载结束
      this.loading = false

      // 判断是否全部加载完，加载完就把finished改为true
      if (this.list.length >= res.data.total) {
        this.finished = true
      }
    }
  }
}
</script>

<style lang="less" scoped>
.article-page {
  margin-bottom: 50px;
  margin-top: 44px;
  .my-nav {
    height: 44px;
    position: fixed;
    left: 0;
    top: 0;
    width: 100%;
    z-index: 999;
    background: #fff;
    display: flex;
    align-items: center;
    > a {
      color: #999;
      font-size: 14px;
      line-height: 44px;
      margin-left: 20px;
      position: relative;
      transition: all 0.3s;
      &::after {
        content: '';
        position: absolute;
        left: 50%;
        transform: translateX(-50%);
        bottom: 0;
        width: 0;
        height: 2px;
        background: #222;
        transition: all 0.3s;
      }
      &.active {
        color: #222;
        &::after {
          width: 14px;
        }
      }
    }
    .logo {
      flex: 1;
      display: flex;
      justify-content: flex-end;
      > img {
        width: 64px;
        height: 28px;
        display: block;
        margin-right: 10px;
      }
    }
  }
}
</style>
